#include "tradehandler.h"
#include <QDebug>
#include "stock/stock.h"

#define TRADE_VALSYMBOLS_CFG_VAR    "TRADE_VAL_SYMBOLS"
#define TRADE_VALNAMES_CFG_VAR      "TRADE_VAL_NAMES"

TradeHandler::TradeHandler(QObject *parent):
    DB(parent),TradeView(parent)
{
    this->flag=NO_FLAG;
}

TradeHandler::TradeHandler(int flag,QObject *parent) :
    DB(parent),TradeView(parent)
{
    this->flag=flag;
}

TradeHandler::TradeHandler(Config *cfg,int flag, QObject *parent):
    DB(parent),TradeView(parent)
{
    if(cfg)
        this->cfg=cfg;
    this->flag=flag;
}

TradeHandler::TradeHandler(const QString &tableName, Config *cfg, int flag, QObject *parent):
    DB(parent),TradeView(parent)
{
    this->tableName=tableName;
    if(cfg)
        this->cfg=cfg;
    this->flag=flag;
}

/*Return all trades of this trade handler*/
QList<Trade *> TradeHandler::getAllTrades() const
{
    return trades.values();
}

/*return all value symbols of the trades*/
QStringList TradeHandler::getValSymbols() const
{
    return QString(TRADE_VALSYMBOLS).split(",");
}

QStringList TradeHandler::getValNames() const
{
    return QString(TRADE_VALNAMES).split(",");
}

/*Get a trade by stock name*/
Trade *TradeHandler::getTrade(const QString &stockName)
{
    return trades.value(stockName);
}

/*Add a trade with the given values and the given stock name*/
void TradeHandler::addTrade(const QString &stockName, const QStringList &values, int flag)
{
    Trade* tmpTrade=new Trade(getValSymbols(),values);           //new trade with value symbols and values
    tmpTrade->setStockName(stockName);                      //set the stock name, this trade belongs to
    if(flag==SHOW_BUY_DIALOG)                               //show the buy dialog, if wanted
    {
        getBuyValues(stockName,tmpTrade);                   //setup the values of this trade with the dialog
    }
}

/*Add a trade to the map and to db*/
void TradeHandler::addTrade(const QString &stockName, Trade *trade)
{
    trades.insert(stockName,trade);                         //add trade to map
    stocks->addStock(stockName,ADD_STOCK_NAME,Global::getStockInstance()->getStocks());             //add the stock name of the trade to the stocks of the tradehandler
    addValues(tableName,trade->getValueMap());              //add trade to trade table (tablename given by depot)    
}

/*Overloaded function*/
void TradeHandler::addTrade(Trade *trade, int flag)
{
    addTrade(trade->getStockName(),trade);

    if(flag==BUY_TRADE)             //change the current liquidity value of the depot
    {
        double cLiq=getCurrentLiquidity();   //current liquidity
        double cost=trade->getValue("ASK").toDouble()*trade->getValue("COUNT").toInt(); //costs
        setCurrentLiquidity(cLiq-cost);                //set new current liquidity
    }
}

/*set the table name where all trades of this trade handler are stored*/
void TradeHandler::setTableName(const QString &tableName)
{
    this->tableName=tableName;
}

/*set the configuration*/
void TradeHandler::setConfig(Config *cfg)
{
    this->cfg=cfg;
}

/*init the tradehandler*/
void TradeHandler::init()
{
    /*create a stock instance for this trade handler, you can not use the stock instance of the parent depot, because the QStandardItems of the depot stock class are already in use and can not be used for the trade view!*/
    stocks=new Stock(*Global::getStockInstance());

    /*set the values shown in the trade table of the stocks*/
    stocks->setValSymbols(QString(TRADE_STOCK_VALSYMBOLS).split(","));

    //valSymbols=cfg->getVar(TRADE_VALSYMBOLS_CFG_VAR);               //read value symbols of a trade
    //valNames=cfg->getVar(TRADE_VALNAMES_CFG_VAR);                   //read the names of the symbols
    if(!tableName.isEmpty() && flag!=DONT_INIT_VALUES)              //table name is set and values can be loaded
    {
        if(!addTable(tableName,QString(TRADE_VALSYMBOLS).split(",")))                         //add table, if it does not exist, load values, if table existed
        {
            qDebug()<<"Table for TradeHandler created";

            QList<QMap<QString,QVariant> > res;
            res=getInnerJoinValues(tableName,STOCK_TABLE,QString(TRADE_VALSYMBOLS).split(",").first(),"ID",QString(TRADE_VALFIELDS).split(","));
            QList<QMap<QString,QVariant> >::iterator iter;
            for(iter=res.begin();iter!=res.end();++iter)            //iter through all trades of this trade handler
            {
                qDebug()<<"Iterating...";
                QMap<QString,QVariant> tmpMap=*iter;                //values of trade from db
                Trade* tmp=new Trade();                             //create a new trade
                QString tmpStockName=tmpMap.value(STOCK_NAME_FIELD).toString();             //get the stock name
                qDebug()<<"TradeHandler::init(): "<<"Adding trade for stock "<<tmpStockName;
                tmpMap.remove(STOCK_NAME_FIELD);                    //remove the stock name field to get only the trade values
                stocks->addStock(tmpStockName,ADD_STOCK_NAME);      //add the stock name of the trade to the stocks of the tradehandler
                tmp->setStockName(tmpStockName);                    //set the stock name of the trade
                tmp->addValue(tmpMap);                              //add trade values stored in the db to the trade
                trades.insert(tmpStockName,tmp);                    //add the trade to map
            }
            qDebug()<<"TradeHandler completly created";
        }
    }
    TradeView::init();                                              //init the tradeview of this tradehandler to show all loaded trades
}

/*returns the stocks of this tradehandler*/
Stock *TradeHandler::getTradeStocks()
{
    return stocks;
}


